import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useUserStore } from '@/stores/userStore.js'
import { insertCartAPI, findNewCartListAPI, deleteCartAPI } from '@/apis/cart.js'

export const useCartStore = defineStore('cart', () => {
  const userStore = useUserStore()

  const isLogin = computed(() => userStore.userInfo.token)

  const cartList = ref([])

  // 获取最新购物车列表action
  const updateNewList = async () => {
    const res = await findNewCartListAPI()
    cartList.value = res.data.result
  }

  // 添加购物车
  const addCart = async (goods) => {
    const { skuId, count } = goods
    if (isLogin.value) {
      // 已登录
      await insertCartAPI({ skuId, count })
      updateNewList()
    } else {
      // 未登录
      const item = cartList.value.find((item) => goods.skuId === item.skuId)
      if (item) {
        item.count++
      }
      else {
        cartList.value.push(goods)
      }
    }
  }

  // 删除购物车
  const delCart = async (skuId) => {
    if (isLogin.value) {
      // 登录
      // 调用购物车删除功能接口
      await deleteCartAPI([skuId])
      updateNewList()
    } else {
      // 未登录
      cartList.value = cartList.value.filter(item => item.skuId !== skuId)
    }
  }

  // 退出登录后清除购物车
  const clearCart = () => {
    cartList.value = []
  }

  // 计算属性
  // 总数量
  const allCount = computed(() => {
    return cartList.value.reduce((a, b) => a + b.count, 0)
  })
  // 总价格
  const allPrice = computed(() => {
    return cartList.value.reduce((a, b) => a + b.count * b.price, 0)

  })

  // 单选功能
  const singleCheck = (skuId, selected) => {
    const item = cartList.value.find((item) => item.skuId === skuId)
    item.selected = selected
  }

  // 是否全选
  const isAllCheck = computed(() => {
    return cartList.value.every((item) => item.selected)
  })

  // 全选功能
  const allCheck = (selected) => {
    cartList.value.forEach((item) => (item.selected = selected))
  }

  // 已选择数量
  const selectedCount = computed(() => {
    return cartList.value
      .filter((item) => item.selected)
      .reduce((a, b) => a + b.count, 0)
  })

  // 已选择商品合计
  const selectedPrice = computed(() => {
    return cartList.value
      .filter((item) => item.selected)
      .reduce((a, b) => a + b.count * b.price, 0)
  })

  return { 
    cartList, 
    allPrice, 
    allCount, 
    isAllCheck, 
    selectedPrice, 
    selectedCount, 
    addCart, 
    delCart, 
    singleCheck, 
    allCheck, 
    clearCart,
    updateNewList
  }
}, {
  persist: true
})

export default useCartStore